package com.devops.controller;

import com.devops.dto.ApiResponse;
import com.devops.dto.LoginRequest;
import com.devops.dto.UserInfo;
import com.devops.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@Validated
@CrossOrigin(origins = "*") // 允许跨域请求
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, Object>>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            UserInfo userInfo = userService.login(loginRequest);
            
            if (userInfo != null) {
                // 登录成功
                Map<String, Object> data = new HashMap<>();
                data.put("user", userInfo);
                data.put("token", "mock-jwt-token-" + userInfo.getId()); // 模拟JWT token
                
                return ResponseEntity.ok(ApiResponse.success("登录成功", data));
            } else {
                // 登录失败
                return ResponseEntity.ok(ApiResponse.error("用户名或密码错误"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("登录失败：" + e.getMessage()));
        }
    }
}
